var colors = require('colors');
var client = require('scp2')
var path = require('path');
var fs = require('fs');
var config = require('./config');

var SSH = require('simple-ssh');

const TARGET = process.env.npm_lifecycle_event;

var ssh = new SSH({
    host: config[TARGET].host,
    user: config[TARGET].user,
    pass: config[TARGET].pass,
    baseDir:config[TARGET].baseDir
});

console.log(colors.yellow('正在发布文件到'+config[TARGET].name+' ...'));

var promises = [];
for(var i=0;i<config.files.length;i++){
    var file = config.files[i];
    promises.push(new Promise(function(resolve, reject){
        client.scp(file, config[TARGET].user+':'+config[TARGET].pass+'@'+config[TARGET].host+':'+config[TARGET].baseDir+'/'+file, function(err) {
          if(err){
            console.error(file+'------'+err)
            reject()
          }
          else{
            resolve()
          }
    })}))
}

Promise.all(promises).then(function(){
  console.log('发布成功'.green);
  console.log('正在修改文件权限'.yellow);
  //修改权限
  ssh.exec('chmod -R 777 .',{
    err: function(stderr) {
        console.log(stderr); // this-does-not-exist: command not found
    }
  }).start()
}).catch(function(e){
    console.error('发布失败')
})
